﻿using System;
using System.Data;
using System.Windows.Forms;
using Litografia.BusinessComponents;
using Litografia.BusinessEntities;
using Nortec.Security;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win;

namespace Litografia.UI.Reports
{
    public partial class BusquedaOTForm : BaseForm
    {
        #region Constructors

        public BusquedaOTForm()
        {
            InitializeComponent();
        }

        #endregion
        
        #region Declarations
        BEOTEntregaSearch.EntregaDataTable lastSearch;
        #endregion

        #region Event Handlers
        
        private void BusquedaOTForm_Load(object sender, EventArgs e)
        {
            ConfigureToolBar(toolStrip, ToolBarButtons.Search);
            toolStrip.ItemClicked += ToolStripItemClicked;
            PopulateStatusComboBox(cmbStatus);
        }
        
        private void ToolStripItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                switch ((ToolBarButtons)e.ClickedItem.Tag)
                {
                    case ToolBarButtons.Search:
                        Search();
                        break;
                    case ToolBarButtons.Close:
                        Close();
                        break;
                }
            }
            finally
            {
                Cursor = Cursors.Arrow;
            }
        }
        
        private void ordenesGrid_DoubleClickRow(object sender, DoubleClickRowEventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (ordenesGrid.Selected.Rows.Count > 0)
                {
                    var numeroOT = (string)ordenesGrid.Selected.Rows[0].Cells[lastSearch.NumeroOTColumn.Ordinal].Value;
                    var entregaId = (int)ordenesGrid.Selected.Rows[0].Cells[lastSearch.EntregaIdColumn.Ordinal].Value;
                    var report = new ReportViewerForm { ReportTitle = ("Detalle - OT #" + numeroOT) };
                    DataSet data = BCOrdenTrabajo.RegistroOTDetalleReporteGet(entregaId);
                    report.BuildReport(data, "Litografia.UI.Reports.OTDetalle.rdlc");
                    ShowScreen(report);
                }
            }
            finally
            {
                Cursor = Cursors.Arrow;
            }
        }
        
        private void datesInSearchCheck_CheckedChanged(object sender, EventArgs e)
        {
            ToggleDates();
        }

        private void txtNumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
                Search();
        }
        
        #endregion

        #region Methods: Private

        private void Search()
        {
            var validEntries = true;
            var number = ((String.IsNullOrEmpty(txtNumber.Text.Trim())) ? null : txtNumber.Text.Trim());
            int? statusId = null;
            DateTime? beginDate = null, endDate = null;

            var selValue = ((BEEntity) cmbStatus.SelectedItem).Id;
            if (!string.IsNullOrEmpty(selValue))
                statusId = int.Parse(selValue);

            if (datesInSearchCheck.Checked)
            {
                var t1 = dateBegin.Value.Date;
                var t2 = dateEnd.Value.Date;
                beginDate = t1;
                endDate = t2;
                
                if (DateTime.Compare(t1, t2) > 0){
                    validEntries = false;
                    ShowError("La fecha fin debe ser mayor a la fecha de inicio");
                }
            }

            if (validEntries)
            {
                lastSearch = BCOrdenTrabajo.SearchOTEntrega(number, statusId, beginDate, endDate, NortecMembership.CompanyId);
                ordenesGrid.DataSource = lastSearch;
                ConfigureOrdenesGrid();
            }
        }
        
        public void ToggleDates()
        {
            dateBegin.Enabled = datesInSearchCheck.Checked;
            dateEnd.Enabled = datesInSearchCheck.Checked;
        }

        private void ConfigureOrdenesGrid()
        {
            // Oculta algunas columnas 
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.IdColumn.Ordinal].Hidden = true;
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.ClienteIdColumn.Ordinal].Hidden = true;
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.ArticuloIdColumn.Ordinal].Hidden = true;
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.EstadoIdColumn.Ordinal].Hidden = true;
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.EntregaIdColumn.Ordinal].Hidden = true;

            // Alineamientos
            foreach (var col in ordenesGrid.DisplayLayout.Bands[0].Columns)
                col.Header.Appearance.TextHAlign = HAlign.Center;
            
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.UnidadesSolicitadasColumn.Ordinal].CellAppearance.TextHAlign = HAlign.Right;
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.FechaInicialColumn.Ordinal].CellAppearance.TextHAlign = HAlign.Center;
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.FechaFinalColumn.Ordinal].CellAppearance.TextHAlign = HAlign.Center;

            // Ancho de columnas
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.NumeroOTColumn.Ordinal].Width = 80;
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.EntregaColumn.Ordinal].Width = 50;
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.UnidadesSolicitadasColumn.Ordinal].Width = 95;
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.FechaInicialColumn.Ordinal].Width = 65;
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.FechaFinalColumn.Ordinal].Width = 65;
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.ClienteNombreColumn.Ordinal].Width = 180;
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.ArticuloNombreColumn.Ordinal].Width = 180;
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.EstadoColumn.Ordinal].Width = 70;

            // Filters
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.NumeroOTColumn.Ordinal].AllowRowFiltering = DefaultableBoolean.False;
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.FechaInicialColumn.Ordinal].AllowRowFiltering = DefaultableBoolean.False;
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.FechaFinalColumn.Ordinal].AllowRowFiltering = DefaultableBoolean.False;
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.ClienteNombreColumn.Ordinal].AllowRowFiltering = DefaultableBoolean.False;
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.ArticuloNombreColumn.Ordinal].AllowRowFiltering = DefaultableBoolean.False;
            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.EstadoColumn.Ordinal].AllowRowFiltering = DefaultableBoolean.False;


            ordenesGrid.DisplayLayout.Bands[0].Columns[lastSearch.UnidadesSolicitadasColumn.Ordinal].Format = "#,##0.00";

            ordenesGrid.DisplayLayout.Bands[0].Override.CellClickAction = CellClickAction.RowSelect;
        }
        
        #endregion
     }
}
